﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Jy123.Web.AppCode;

namespace Jy123.Web.Album
{
    public partial class PhotoUpload : System.Web.UI.Page
    {
        private int userID ;//暂用用户ID，写死，到时候用COOKIE替换过来
        string upLoadedPath = "";
        Common.Upload upload = new Jy123.Common.Upload();
        AppCode.CreateDir createDir = new Jy123.Web.AppCode.CreateDir();
        protected void Page_Load(object sender, EventArgs e)
        {
            string strUserIdFromCookie = Common.Cookie.getCookie("UserID");
            if (string.IsNullOrEmpty(strUserIdFromCookie))
            {
                Response.Redirect("/");
            }
            userID = int.Parse(strUserIdFromCookie);

            //string upfiles = Request["filepic"];
            //upfiles.Split(',');
            string msg =string.Empty;

            string albumID = Request.QueryString["AlbumID"];
            string strupload = Request.Form["upload"];
            if (strupload == "上传照片")
            {

                albumID = Request.Form["hidUpload"];
                if (!string.IsNullOrEmpty(albumID))
                {
                    System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                    int isNullCount = 0;//文件为空的计数器

                    //检查所有上传按钮是否全部为空
                    for (int j = 0; j < files.Count; j++)
                    {
                        HttpPostedFile postFile = files[j];
                        string photoPath = postFile.FileName;
                        if (string.IsNullOrEmpty(photoPath)) { isNullCount += 1; }//如果出现文件为空，计数器+1
                    }
                    if (isNullCount < files.Count)//当上传控件不全为空则开始上传
                    {
                        string strPhotoIDs = UploadPhotos(int.Parse(albumID));//批量上传照片
                        Jy123.Model.User_Album mUpAlbum = new Jy123.Model.User_Album();
                        Jy123.BLL.User_Album bllUpAlbum = new Jy123.BLL.User_Album();
                        mUpAlbum = bllUpAlbum.GetModel(Convert.ToInt32(albumID));
                        mUpAlbum.LastUploadTime = DateTime.Now;
                        bllUpAlbum.Update(mUpAlbum);

                        //加入动态
                        Jy123.Model.User_Main mUserForState = new Jy123.Model.User_Main();
                        Jy123.BLL.User_Main bllUserForState = new Jy123.BLL.User_Main();
                        mUserForState = bllUserForState.GetModel(userID);

                        Jy123.Model.User_Album mAlbumForState = new Jy123.Model.User_Album();
                        Jy123.BLL.User_Album bllAlbumForState = new Jy123.BLL.User_Album();
                        mAlbumForState = bllAlbumForState.GetModel(Convert.ToInt32(albumID));
                        new Jy123.BLL.Public.State().CreatePhotoState(mUserForState, mAlbumForState, strPhotoIDs, string.Empty);//创建照片的动态
                        //加入动态

                        Response.Redirect("/Album/PhotoEdit.aspx?AlbumID=" + albumID);
                    }
                    else
                    {
                        msg = "<script>$(function(){$.moonbox.warning('文件为空，不可上传!');})</script>";
                    }
                }
            }

            #region 公共部分
            StringBuilder strHtml = new StringBuilder(Cache["user_photoupload"].ToString());//取得主HTML页面
            strHtml = strHtml.Replace("$Header$", Cache["user_header2"].ToString());
            strHtml = strHtml.Replace("$Footer$", Cache["user_footer"].ToString());
            strHtml = strHtml.Replace("$LeftUserCmd$", Cache["user_navigation_down"].ToString());
            strHtml = strHtml.Replace("$LeftUserFriendAdd$", Cache["user_friendadd"].ToString());

            ////统计站内信数量
            //Jy123.BLL.User.Letter bllLetter = new Jy123.BLL.User.Letter();
            //int newLetterCount = bllLetter.CountNewLetter(userID);
            //strHtml = strHtml.Replace("$NewMsg$", newLetterCount.ToString());
            #endregion
            strHtml = strHtml.Replace("$hidUpload$", albumID);
            Response.Write(strHtml.ToString()+msg);
        }
        /// <summary>
        /// 批量上传多个照片
        /// </summary>
        private string UploadPhotos(int albumID)
        {
            StringBuilder sbPhotoIDs=new StringBuilder();
            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            bool fileOK = false;
            //int uploadedCount = 0;//成功上传的数量 
            
                #region 批量上传
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile postFile = files[i];
                    string photoPath = postFile.FileName;
                    if (string.IsNullOrEmpty(photoPath)) { continue; }

                    string photoName = string.Empty;
                    if (upload.IsPic(photoPath))//判断文件是否为图片类型
                    {
                        fileOK = true;
                    }
                    else
                    {
                        Response.Write("文件必须为.gif, .png, .bmp, .jpg等类型");
                    }

                    if (fileOK)
                    {
                        string photoType = photoPath.Substring(photoPath.LastIndexOf(".") + 1);
                        photoName = createDir.CreatePhotoPath(CreateDir.USER, userID, DateTime.Now, photoType);
                        string mapPath = Server.MapPath("/");

                        upload.PostedFile = postFile;
                        upload.FileLength = postFile.ContentLength;
                        upload.FileName = photoName;
                        upload.Extension = photoType;
                        upload.SavePath = mapPath;
                        upload.UploadStart(photoName);
                        upLoadedPath = photoName;
                    }

                    Jy123.Model.User_Photo mPhoto = new Jy123.Model.User_Photo();
                    Jy123.BLL.User_Photo bllPhoto = new Jy123.BLL.User_Photo();
                    mPhoto.FAlbum = albumID;
                    mPhoto.FUser = userID;
                    mPhoto.Description = "无描述";
                    mPhoto.Views = 0;
                    mPhoto.FileSize = upload.FileLength;
                    mPhoto.State = 0;
                    mPhoto.IsCover = false;
                    mPhoto.Comments = 0;
                    mPhoto.PostTime = DateTime.Now;
                    mPhoto.PostIP = Common.Public.GetClientIP();
                    mPhoto.IsLock = false;
                    mPhoto.PhotoType = 1;
                    mPhoto.FilePath = upLoadedPath;
                    int newPhotoID = bllPhoto.Add(mPhoto);

                    if (newPhotoID > 0)
                    {
                        sbPhotoIDs.Append("," + newPhotoID.ToString());
                        //uploadedCount += 1;
                    }
                }
            string strPhotoIDs =sbPhotoIDs.ToString();
                if (!string.IsNullOrEmpty(strPhotoIDs))
                {
                    strPhotoIDs = strPhotoIDs.Substring(1);
                }
                #endregion
                return strPhotoIDs;
                ////更新该相册中的相片数量值
                //Jy123.Model.User_Album mAlbum = new Jy123.Model.User_Album();
                //Jy123.BLL.User_Album bllAlbum = new Jy123.BLL.User_Album();
                //mAlbum = bllAlbum.GetModel(albumID);
                //mAlbum.ImagesCount += uploadedCount;
                //bllAlbum.Update(mAlbum);
        }
        /// <summary>
        /// 上传单个照片
        /// </summary>
        private void UploadPhoto()
        {
            string strupload = Request.Form["upload"];
            if (strupload == "上传照片")
            {
                System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

                bool fileOK = false;
                //HttpPostedFile[] postFile = new HttpPostedFile[upfiles.Length];
                HttpPostedFile postFile = files[0];// FileUpload1.PostedFile;
                //for (int i = 0; i < upfiles.Length; i++)
                //{
                //    System.Web.HttpPostedFile file = files[i];

                //}

                //HttpPostedFile postFile =  new HttpPostedFile();
                //postFile.FileName = upfiles;

                //postFile.FileName
                //HttpPostedFile postFile = Request.Form["filepic"];//FileUpload1.PostedFile;
                string photoPath = postFile.FileName;
                string photoName = string.Empty;

                if (upload.IsPic(photoPath))//判断文件是否为图片类型
                {
                    fileOK = true;
                }
                else
                {
                    Response.Write("文件必须为.gif, .png, .bmp, .jpg等类型");
                }

                if (fileOK)
                {
                    string photoType = photoPath.Substring(photoPath.LastIndexOf(".") + 1);
                    photoName = createDir.CreatePhotoPath(CreateDir.USER, userID, DateTime.Now, photoType);
                    string mapPath = Server.MapPath("/");

                    upload.PostedFile = postFile;
                    upload.FileLength = postFile.ContentLength;
                    upload.FileName = photoName;
                    upload.Extension = photoType;
                    upload.SavePath = mapPath;
                    upload.UploadStart(photoName);

                    upLoadedPath = photoName;
                }
            }
        }


    }
}
